/*
 * Copyright (C) 2010 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.tracking.internal.injection;

import java.io.*;

/**
 * Utility class for injection stuff.
 * 
 * @author M. Hautle
 * @since 18.12.2010
 */
public class InjectionUtils {
    /**
     * Hidden constructor.
     */
    private InjectionUtils() {
    }

    /**
     * Reads the bytecode of a class.
     * 
     * @param is an input stream from which to read the class (will be closed)
     * @return the bytecode read from the given input stream.
     * @throws IOException if a problem occurs during reading.
     */
    public static byte[] readClass(final InputStream is) throws IOException {
        if (is == null)
            throw new IOException("Class not found");
        try {
            byte[] b = new byte[is.available()];
            int len = 0;
            while (true) {
                final int n = is.read(b, len, b.length - len);
                if (n == -1) {
                    if (len < b.length) {
                        final byte[] c = new byte[len];
                        System.arraycopy(b, 0, c, 0, len);
                        b = c;
                    }
                    return b;
                }
                len += n;
                if (len == b.length) {
                    final byte[] c = new byte[b.length + 1000];
                    System.arraycopy(b, 0, c, 0, len);
                    b = c;
                }
            }
        } finally {
            is.close();
        }
    }
}
